package com.jty.module_user.viewmodel

import androidx.databinding.ObservableBoolean
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.GsonUtils
import com.czl.lib_base.config.AppConstants
import com.jty.lib_base.base.BaseBean
import com.jty.lib_base.base.BaseViewModel
import com.jty.lib_base.base.MyApplication
import com.jty.lib_base.binding.command.BindingAction
import com.jty.lib_base.binding.command.BindingCommand
import com.jty.lib_base.bus.event.SingleLiveEvent
import com.jty.lib_base.data.DataRepository
import com.jty.lib_base.data.bean.SectionBean
import com.jty.lib_base.data.bean.SubjectBean
import com.jty.lib_base.data.bean.UserInfoBean
import com.jty.lib_base.extension.ApiSubscriptHelper
import com.jty.lib_base.utils.ComUtils
import com.jty.lib_base.utils.RxThreadHelper
import com.jty.module_user.data.DialogData
import com.jty.module_user.obj.DialogType
import okhttp3.RequestBody


/**
 * author: zhouyh
 * created on: 2021/9/18 5:35 下午
 * description:主页viewmodel
 */
class DataViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {

    var userInfoBean = MutableLiveData<UserInfoBean>(model.getUserInfoData())
    var isSupplement = MutableLiveData<Boolean>(false)
    var sectionList : MutableList<SectionBean> ?= null
    var subjectList : MutableList<SubjectBean> ?= null
    var userInfoUpdate:ObservableBoolean = ObservableBoolean(false)

    val uc = UIChangeEvent()

    /**
     * UI刷新事件 用于观察者
     */
    class UIChangeEvent{
        val show4Dialog: SingleLiveEvent<Int> = SingleLiveEvent()
        val showAvatarDialog:SingleLiveEvent<Void> = SingleLiveEvent()
        val saveUserInfoEvent:SingleLiveEvent<Void> = SingleLiveEvent()
        val updateUserInfoSuccess:SingleLiveEvent<Void> = SingleLiveEvent()
    }

    override fun onCreate() {
        super.onCreate()
        tvTitle.set("个人资料")
        getUserInfo()
        getSectionList()
        getSubjectList()
    }


    /**
     * 学段
     */
    val showPhaseDialog: BindingCommand<Void> = BindingCommand(BindingAction {
        uc.show4Dialog.postValue(DialogType.PHASE)
    })

    /**
     * 学科
     */
    val showSubjectDialog: BindingCommand<Void> = BindingCommand(BindingAction {
        uc.show4Dialog.postValue(DialogType.SUBJECT)
    })


    /**
     * 手机
     */
    val onClickModifyPhone: BindingCommand<Void> = BindingCommand(BindingAction {
        startContainerActivity(AppConstants.Router.User.F_MODIFYPHONE)
    })

    /**
     * 头像
     */
    val showAvatarDialog:BindingCommand<Void> = BindingCommand(BindingAction {
        uc.showAvatarDialog.call()
    })


    override fun finish() {
        uc.saveUserInfoEvent.call()
    }

    fun modifyPhoneSuccess(phone: String) {
        val bean = model.getUserInfoData()
        bean?.mobile = phone
        userInfoBean.value?.mobile = phone
        model.saveUserInfoData(bean!!)
        userInfoBean.postValue(userInfoBean.value)
    }


    fun setIsSupplement(b:Boolean){
        isSupplement.postValue(b)
        isSupplement.value?.let {
            if(it) {
                tvTitle.set("补充个人资料")
            } else {
                tvTitle.set("个人资料")
            }
        }
    }


    /**
     * 更新学科
     */
    fun changeSubject(g: DialogData){
        userInfoUpdate.set(true)
        userInfoBean.value?.subjectId = g.id
        userInfoBean.value?.subject = g.name!!
        userInfoBean.postValue(userInfoBean.value)
    }

    /**
     * 更新学段
     */
    fun changeSection(g:DialogData){
        userInfoUpdate.set(true)
        userInfoBean.value?.sectionId = g.id
        userInfoBean.value?.section = g.name!!
        userInfoBean.postValue(userInfoBean.value)
    }


    /**
     * 获取用户信息
     */
    private fun getUserInfo() {
        model.apply {
            getUserInfo()
                .compose(RxThreadHelper.rxSchedulerHelper(this@DataViewModel))
                .subscribe(object : ApiSubscriptHelper<BaseBean<UserInfoBean>>() {
                    override fun onResult(t: BaseBean<UserInfoBean>) {
                        //Logger.e(t.toString())
                        dismissLoading()
                        if (t.code == 0) {
                            t.data?.let {
                                userInfoBean.postValue(it)
                            }
                        }
                    }
                    override fun onFailed(msg: String?) {
                        showNormalToast(msg)
                    }
                })
        }
    }

    /**
     * 获取学段列表
     */
    fun getSectionList(){
        model.apply {
            querySection()
                .compose(RxThreadHelper.rxSchedulerHelper(this@DataViewModel))
                .subscribe(object : ApiSubscriptHelper<BaseBean<List<SectionBean>>>(){
                    override fun onResult(t: BaseBean<List<SectionBean>>) {
                        if (t.code == 0){
                            sectionList = t.data as MutableList<SectionBean>?
                        }
                    }
                    override fun onFailed(msg: String?) {

                    }
                })
        }
    }

    /**
     * 获取学科列表
     */
    fun getSubjectList(){
        model.apply {
            querySubject()
                .compose(RxThreadHelper.rxSchedulerHelper(this@DataViewModel))
                .subscribe(object : ApiSubscriptHelper<BaseBean<List<SubjectBean>>>(){
                    override fun onResult(t: BaseBean<List<SubjectBean>>) {
                        if (t.code == 0){
                            subjectList = t.data as MutableList<SubjectBean>?
                        }
                    }
                    override fun onFailed(msg: String?) {

                    }
                })
        }
    }


    fun modifyUserInfo() {
        var json = ComUtils.getHashmapByStr(
            arrayOf("sectionId","subjectId","avatarUrl"),
            arrayOf(userInfoBean.value?.sectionId!!,userInfoBean.value?.subjectId!!,userInfoBean.value?.avatarUrl?:"")
        )
        val requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
            GsonUtils.toJson(json))
        model.apply {
            this.modifyUserInfo(requestBody)
                .compose(RxThreadHelper.rxSchedulerHelper(this@DataViewModel))
                .subscribe(object : ApiSubscriptHelper<BaseBean<Any?>>() {
                    override fun onResult(t: BaseBean<Any?>) {
                        //Logger.e(t.toString())
                        dismissLoading()
                        if (t.code == 0) {
                            showNormalToast("修改成功")
                            saveUserInfoData(userInfoBean.value!!)
                            uc.updateUserInfoSuccess.call()
                        }
                    }
                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showNormalToast(msg)
                    }
                })
        }
    }


    /**
     * 修改头像
     */




}